
import { nextTick, ComponentPublicInstance } from "vue";


/** 工具函数 */
const useFunction = () => {
	return {
		/** 显示消息提示框 */
		toast: (options: string | UniNamespace.ShowToastOptions) => {
			options = typeof options === 'string' ? { title: options, icon: 'none' } : options;
			uni.showToast(options);
		},
		
		/** 获取节点 */
		getRect: function(selector: string, proxy: ComponentPublicInstance) {
			return new Promise<UniNamespace.NodeInfo>(resolve => {
				nextTick(() => {
					uni.createSelectorQuery()
						.in(proxy)
						.select(selector)
						.boundingClientRect(result => resolve(result as UniNamespace.NodeInfo))
						.exec();
				});
			});
		},
		
		/** 函数防抖 */
		debounce: function(func: Function, wait = 1000, immediate = true) {
			let timer: NodeJS.Timeout;
			return function() {
				const context = this;
				const args = arguments;
				if (timer) clearTimeout(timer);
				if (immediate) {
					let callNow = !timer;
					timer = setTimeout(() => {
						timer = null;
						
					}, wait);
					
					if (callNow) func.apply(context, args);
					
				} else {
					timer = setTimeout(() => {
						func.apply(context, args);
						
					}, wait)
				};
			};
		},
	};
};


export default useFunction;